package com.xw.tools.util;

import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;

public class Base64Util {

    public static String encode(String text, String charset) {
        try {
            return Base64.getEncoder().encodeToString(text.getBytes(charset));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String encode(String filePath) {
        try {
            byte[] bytes = Files.readAllBytes(Paths.get(filePath));
            return Base64.getEncoder().encodeToString(bytes);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decode(String text, String charset) {
        try {
            text = text.replaceAll(" ", "");
            text = text.replaceAll("\n|\r|\t", "");
            return new String(Base64.getDecoder().decode(text), charset);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static boolean decodeToFile(String text, String filePath) {
        try {
            text = text.replaceAll(" ", "");
            text = text.replaceAll("\n|\r|\t", "");
            byte[] bytes = Base64.getDecoder().decode(text);
            Files.write(Paths.get(filePath), bytes);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }
}
